<template>
    <Layout class="menu-left">
        <Form ref="queryForm" :model="dataToQuery" style="margin-top: 10px;" :label-width="120">
            <Row class="query-form" >
                <Col span="8">
                    <FormItem label="企业名称：" prop="order">
                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyId' :orgTree="true"
                                    :currentOrgId="dataToQuery.companyId"
                                    :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label='设备型号：' prop='deviceTypeName'>
                        <Select v-model="dataToQuery.deviceTypeName" style="width:200px" @on-select="queryDevice">
                            <Option v-for="item in deviceTypeList" :value="item.deviceCollectionItemId" :key="item.deviceCollectionItemId">{{ item.deviceTypeName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label='设备：' prop='deviceName'>
                        <Select v-model="dataToQuery.deviceName" style="width:200px" @on-select="selectDeviceName">>
                            <Option v-for="item in deviceList" :value="item.deviceInfoId" :key="item.deviceInfoId">{{ item.deviceName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="24">
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search"  @click="query">查询</Button>
                </Col> 
            </Row>
        </Form>
        <div  ref="realTimeLineContainer" :style="{width: '100%', height: 'calc(100vh - 210px)'}"></div>
    </Layout>
</template>

<script>
    import * as echarts from 'echarts';
    import cascaderDom from "../../../components/cascader-dom.vue"
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {MqttConfig} from '@/api/mqttconstant.js';
    import mqtt from 'mqtt';
    import {
        Api
    } from '../../../api/index.js'
    export default {
        components: {
            cascaderDom
        },
        data() {
            return {
                ...this.createCommonDataField(),
                codes:[],
                serialSet:[],
                deviceTypeList:[],
                deviceList:[],
                realTimeLineContainer:null,
                realTimeLineOption:{},
                realTimeLineData:[],
                realTimeLineData1:[],
                currentCollectionItemChilds:[],
                lineHeight:300,
                now :new Date(1997, 9, 3),
                oneDay : 24 * 3600 * 1000,
                value : Math.random() * 1000
            }
        },
        mounted(){
            this.lineHeight = window.innerHeight - 150;
            this.realTimeLineOption = this.loadRealTimeLine();
            var that = this;
        /*    setInterval(function () {
                that.realTimeLineContainer.setOption({
                    series: that.serialSet
                }); 
            }, 1000);  
            setInterval(function(){
                if(that.realTimeLineData.length > 10){
                    that.realTimeLineData.shift();
                    that.realTimeLineData.push(that.randomData());
                }else{
                    that.realTimeLineData.push(that.randomData());
                }
                if(that.serialSet.length>0)
                    that.serialSet[0].data = that.realTimeLineData;
            },5000);
            setInterval(function(){
                if(that.realTimeLineData1.length > 10){
                    that.realTimeLineData1.shift();
                    that.realTimeLineData1.push(that.randomData()+200);
                }else{
                    that.realTimeLineData1.push(that.randomData()+300);
                }
                if(that.serialSet.length>0)
                    that.serialSet[1].data = that.realTimeLineData1;
            },10000);    */
        },
        methods:{
            ...pageCommonFunction,
            query(){   
                this.$http.get(Api.queryDeviceCollectionItemChildByItemId+"/"+this.dataToQuery.deviceTypeName, {}).then(res => {
                    this.currentCollectionItemChilds = res.data.data.data;
                    this.serialSet = [];
                    this.currentCollectionItemChilds.forEach(item=>{
                        this.codes.push(item.itemCode);
                        this.serialSet.push({
                            name: item.itemName,
                            code:item.itemCode,
                            type: 'line',
                            data:[]
                        })
                    });
                    this.realTimeLineContainer.setOption({
                        serial:this.serialSet
                    })
                    this.linkMqtt();
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            linkMqtt(){
                let client = {};
                client = mqtt.connect(MqttConfig.MQTT_SERVICE, {
                    port: MqttConfig.MQTT_PORT,
                    clientId: 'client_id_'+ new Date().getTime(),
                    username: MqttConfig.MQTT_USERNAME,
                    password: MqttConfig.MQTT_PASSWORD,
                    clean: false,
                });
                let topic = 'data/RealTime/' + this.dataToQuery.deviceTypeName + "/"+ this.dataToQuery.deviceName;
                console.log(topic);
                client.on('connect', function () {
                    client.subscribe(topic, function (err) {
                        console.log("connect success");
                        if (!err) {
                            //DOSOMETHINGS
                        }
                    })
                });
                client.on('message', (topic, message) => {
                    let obj = eval('(' + message.toString() + ')');
                    console.log(message,toString())
                    this.setRtLine(obj)
                })
                this.client = client;
            },
            randomData(t,p) {
                this.now = t;
                this.value = p;
                return {
                    name: this.now.toString(),
                    value: [
                    [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
                    Math.round(this.value)
                    ]
                };
            },  
            randomData1() {
               this.now = new Date(+this.now + this.oneDay);
                this.value = this.value + Math.random() * 21 - 10;
                return {
                    name: this.now.toString(),
                    value: [
                    [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
                    Math.round(this.value)
                    ]
                };
            },
            loadRealTimeLine(){
                this.realTimeLineContainer = echarts.init(this.$refs.realTimeLineContainer);
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            params = params[0];
                            var date = new Date(params.name);
                            return (
                                date.getDate() +
                                '/' +
                                (date.getMonth() + 1) +
                                '/' +
                                date.getFullYear() +
                                ' ' +
                                date.getHours() +
                                '-' +
                                date.getMinutes() +
                                '-' +
                                date.getSeconds() +
                                ' : ' +
                                params.value[1]
                            );
                        },    
                        axisPointer: {
                            animation: false
                        }
                    },
                    xAxis: {
                        type: 'time',
                        splitLine: {
                            show: false
                        }
                    },
                    yAxis: {
                        type: 'value',
                        boundaryGap: [0, '100%'],
                        splitLine: {
                        show: false
                        }
                    },
                    legend:{
                        orient: 'vertical',
                        right: 'right',
                    }
                };
                this.realTimeLineContainer.setOption(option);
                return option;
            },
            setRtLine(obj){
                let now = new Date(obj['time']*1000);
                var valueName = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() +
                ' ' + (now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()) + ':' +
                (now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes()) +
                ':' + (now.getSeconds() >= 10 ? now.getSeconds() : '0' + now.getSeconds());
                let value = obj.value;
                this.codes.map((i, j)=>{
                    let data =  this.serialSet[j].data;
                    let p = value[i];
                    data.push({name:t.toString(),value:[valueName,parseInt(p)]});
                })
                console.log(this.serialSet)
                this.realTimeLineContainer.setOption({
                    series : this.serialSet
                });
            },
            setQueryCompanyId(data) {
                this.$set(this.dataToQuery, 'companyId', data[data.length - 1])
                this.queryDeviceType(this.dataToQuery.companyId);
            },
            queryDeviceType(id){
                var companyId = sessionStorage('userId').getObject('userId').companyId;
                if(id != ""&&id!= undefined)
                    companyId = id;
                this.$http.get(Api.queryDeviceCollectionItemList+"?fromPage=1&pageSize=1000&orgId="+companyId).then(res => {
                    this.deviceTypeList = res.data.data.data;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            queryDevice(id){
                 this.$http.get(Api.queryDeviceByItemId+"/"+id.value).then(res => {
                    this.deviceList = res.data.data.data;
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            }
        }
    }

</script>